import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const requirement = await db.requirement.findUnique({
      where: { id: params.id },
      include: {
        project: {
          select: { id: true, name: true, key: true }
        },
        iteration: {
          select: { id: true, name: true }
        },
        hardwareVersion: {
          select: { id: true, version: true, name: true }
        },
        bom: {
          select: { id: true, version: true, name: true }
        },
        creator: {
          select: { id: true, name: true, username: true, email: true }
        },
        assignee: {
          select: { id: true, name: true, username: true, email: true }
        },
        tasks: {
          include: {
            creator: {
              select: { id: true, name: true, username: true }
            },
            assignee: {
              select: { id: true, name: true, username: true }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        bugs: {
          include: {
            creator: {
              select: { id: true, name: true, username: true }
            },
            assignee: {
              select: { id: true, name: true, username: true }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        comments: {
          include: {
            author: {
              select: { id: true, name: true, username: true }
            }
          },
          orderBy: { createdAt: 'desc' }
        },
        attachments: {
          orderBy: { createdAt: 'desc' }
        },
        _count: {
          select: {
            tasks: true,
            bugs: true,
            comments: true,
            attachments: true
          }
        }
      }
    })

    if (!requirement) {
      return NextResponse.json(
        { error: 'Requirement not found' },
        { status: 404 }
      )
    }

    return NextResponse.json(requirement)
  } catch (error) {
    console.error('Error fetching requirement:', error)
    return NextResponse.json(
      { error: 'Failed to fetch requirement' },
      { status: 500 }
    )
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const body = await request.json()
    const {
      title,
      description,
      type,
      priority,
      status,
      assigneeId,
      estimate,
      spent
    } = body

    const requirement = await db.requirement.update({
      where: { id: params.id },
      data: {
        ...(title && { title }),
        ...(description !== undefined && { description }),
        ...(type && { type }),
        ...(priority && { priority }),
        ...(status && { status }),
        ...(assigneeId !== undefined && { assigneeId }),
        ...(estimate !== undefined && { estimate }),
        ...(spent !== undefined && { spent })
      },
      include: {
        project: {
          select: { id: true, name: true, key: true }
        },
        iteration: {
          select: { id: true, name: true }
        },
        creator: {
          select: { id: true, name: true, username: true }
        },
        assignee: {
          select: { id: true, name: true, username: true }
        }
      }
    })

    return NextResponse.json(requirement)
  } catch (error) {
    console.error('Error updating requirement:', error)
    return NextResponse.json(
      { error: 'Failed to update requirement' },
      { status: 500 }
    )
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    await db.requirement.delete({
      where: { id: params.id }
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting requirement:', error)
    return NextResponse.json(
      { error: 'Failed to delete requirement' },
      { status: 500 }
    )
  }
}